//
//  CZTabBar.swift
//  weiBo
//
//  Created by apple on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//设置代理
protocol CZTabBarDelegate:NSObjectProtocol{
    //点击按钮回调的方法
    func didSelectedComposeButton()
}

class CZTabBar: UITabBar {
    //设置闭包
    var composeButtonClousre: (()->())?
    //设置遵守了代理的属性
    weak var czDelegate : CZTabBarDelegate?
//懒加载创建加号按钮

    private lazy var composeButton: UIButton =
    {
        let btn = UIButton()
        //添加背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        //添加事件
        btn.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        btn.sizeToFit()
        
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        setBtn()
        
    }
    
    private func setBtn(){
        addSubview(composeButton)

    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        //计算视图按钮的大小
        let width = frame.size.width * 0.2
        //记录第几个空间
        var index = 0
        //遍历tabbar里面的所有的空间
        for childView in subviews
        {
            if childView .isKindOfClass(NSClassFromString("UITabBarButton")!)
            {
                childView.frame.size.width = width
                childView.frame.origin.x = CGFloat(width) * CGFloat(index)
                    index++
                if index == 2
                {
                    index++
                }
            }
        }
    }
    
    //加号点击事件
    @objc private func composeButtonClick()
    {
//        print("haha")
        //执行闭包
        composeButtonClousre?()
        
        czDelegate?.didSelectedComposeButton()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    
    
    
    
}
